<style lang="less">
    @import "./style.less";
</style>

<template>
    <div class="trainee">
        <div class="op-header">
            <el-button @click="add" class="add" type="info" v-has="110403">
                <i class="el-icon-circle-plus icon-right" />新增学员
            </el-button>
            <div class="search">
                <el-cascader
                        :options="enableOptions"
                        :props="cascaderProps"
                        class="enable-select"
                        placeholder="启用状态"
                        v-model="enableValue"
                />
                <el-cascader
                        :clearable="true"
                        change-on-select
                        :options="torgins"
                        :props="cascaderProps"
                        class="department-select"
                        placeholder="所属部门"
                        v-model="departmentValue"
                />
                <el-input class="search-input" placeholder="请输入查询关键字" prefix-icon="el-icon-search"
                          v-model="searchInput" />
                <el-button @click="search" class="ml" type="primary">
                    <i class="el-icon-search icon-right" /> 查询
                </el-button>
                <el-button @click="exportExcel" class="ml" type="primary">
                    <i class="el-icon-upload2 icon-right" /> 导出
                </el-button>
                <el-upload
                        :data="{organizationId: departmentValue[departmentValue.length - 1]}"
                        :disabled="!departmentValue.length"
                        :show-file-list="false"
                        :on-success="importFileSuccess"
                        :on-error="importFileError"
                        accept="xls, xlsx"
                        action="/api/trainee/import"
                        name="file"
                >
                    <el-button :disabled="!departmentValue.length" class="ml" type="primary">
                        <i class="el-icon-upload icon-right" /> 导入
                    </el-button>
                </el-upload>
                <el-button @click="downloadTemplate" class="ml" type="primary">
                    <i class="el-icon-download icon-right" /> 下载模版
                </el-button>
            </div>
        </div>
        <table-ex
                :columns="columns"
                :on-operation="onClickOperation"
                :on-option="onClickOption"
                :on-page-change="onPageChange"
                :options="options"
                :rows="trainees"
                :total="traineesTotal"
        />
        <dialog-ex
                :ctrl-values="torgins"
                :form="form"
                :init="currentTrainee"
                :mode="dialogModal"
                :title="dialogTitle"
                v-if="!!dialogModal"
        />
        <!-- excel -->
        <table-ex
                :columns="exportColumns"
                :on-operation="onClickOperation"
                :on-option="onClickOption"
                :on-page-change="onPageChange"
                :options="options"
                :rows="trainees"
                :total="traineesTotal"
                ref="excelTable"
                selection="none"
                table-id="traineeExcel"
                v-show="false"
        />
    </div>
</template>

<script>
    import { mapActions, mapGetters, mapMutations } from "vuex";
    import { Message } from "element-ui";
    import pageConfig from "./config";
    import axios from "axios";
    import TableEx from "@/components/table/tableEx";
    import dialogEx from "@/components/dialog/dialogEx";

    export default {
        name: "trainee",
        components: {
            "table-ex": TableEx,
            "dialog-ex": dialogEx
        },
        data() {
            return {
                dialogModal: null,
                dialogTitle: "",
                searchInput: "",
                enableValue: [],
                departmentValue: [],
                columns: pageConfig.columns,
                exportColumns: pageConfig.exportColumns,
                options: pageConfig.options,
                enableOptions: pageConfig.enableOptions,
                cascaderProps: {
                    value: "id",
                    label: "title",
                    children: "children"
                },
                currentTrainee: {},
                form: {
                    items: [],
                    actions: {
                        cancel: () => {
                            this.dialogModal = "";
                        },
                        confirm: (data, mode) => {
                            this.dialogModal = "";
                            if (mode === "add") {
                                if (
                                    data.password === data.confirmPassword &&
                                    (data.password && data.confirmPassword)
                                ) {
                                    this.addTrainee(data);
                                } else {
                                    Message({
                                        center: true,
                                        message: "请确认密码填写正确"
                                    });
                                }
                            } else if (mode === "edit") {
                                this.editTrainee(data);
                            }
                        }
                    }
                }
            };
        },
        computed: {
            ...mapGetters(["trainees", "traineesTotal", "torgins"])
        },
        created() {
            this.loadData();
        },
        methods: {
            ...mapActions([
                "getTrainees",
                "addTrainee",
                "editTrainee",
                "removeTrainee",
                "getTOrgans",
                "uploadTraineeTemplete"
            ]),
            ...mapMutations(["SETTRAINEEPAGE"]),

            loadData() {
                this.getTrainees();
                this.getTOrgans();
            },

            add() {
                console.log(this.departements);
                this.dialogTitle = "新增学员";
                this.dialogModal = "add";
                this.form.items = pageConfig.addFormItems;
                console.log(this.form.items);
            },

            search() {
                const filter = {
                    name: this.searchInput ? this.searchInput : null,
                    enabled: !!this.enableValue ? this.enableValue[0] : null,
                    orgIds: this.departmentValue && this.departmentValue.length > 0 ? [this.departmentValue[this.departmentValue.length - 1]] : null
                };
                this.SETTRAINEEPAGE({
                    number: 1,
                    filter
                });
                this.getTrainees();
            },

            exportExcel() {
                this.$refs.excelTable.exportExcel();
            },
            importFileSuccess(response, file, fileList) {
                this.$message({
                    message: `${file.name} 导入成功`,
                    type: "success"
                });
            },

            importFileError(error) {
                const errMessage = error.message ? JSON.parse(error.message) : error
                Message({
                    center: true,
                    message: errMessage.message
                })
                console.error('importFileError', error)
            },

            downloadTemplate() {
                axios({
                    method: "get",
                    url: "/api/trainee/import/templete",
                    responseType: "arraybuffer"
                }).then(response => {
                    let filename = "trainees.xls";
                    this.fileDownload(response.data, filename);
                });
            },
            batchOption() {
            },

            onClickOption(option, rows) {
                if (option === "batchrefresh") {
                    this.loadData();
                } else {
                    console.log(rows);
                    let lIds = rows.map(item => {
                        return item.userId;
                    });
                    this.removeTrainee({ lIds });
                }
            },

            onClickOperation(oper, row) {
                let type = oper.prop;
                this.currentTrainee = row;
                switch (type) {
                    case "edit":
                        this.dialogModal = "edit";
                        this.dialogTitle = "修改学员信息";
                        this.form.items = pageConfig.editFormItems;
                        break;
                    case "delete":
                        let params = {
                            lIds: [row.employeeId]
                        };
                        this.removeTrainee(params);
                        break;
                    default:
                        this.dialogModal = "edit";
                        this.dialogTitle = "重置密码";
                        this.form.items = pageConfig.passwordFormItems;
                }
            },

            onPageChange(number) {
                this.SETTRAINEEPAGE({ number });
                this.getTrainees();
            },

            fileDownload(data, fileName) {
                let blob = new Blob([data], {
                    type: "application/octet-stream"
                });
                let filename = fileName || "filename.xls";
                if (typeof window.navigator.msSaveBlob !== "undefined") {
                    window.navigator.msSaveBlob(blob, filename);
                } else {
                    var blobURL = window.URL.createObjectURL(blob);
                    var tempLink = document.createElement("a");
                    tempLink.style.display = "none";
                    tempLink.href = blobURL;
                    tempLink.setAttribute("download", filename);
                    if (typeof tempLink.download === "undefined") {
                        tempLink.setAttribute("target", "_blank");
                    }
                    document.body.appendChild(tempLink);
                    tempLink.click();
                    document.body.removeChild(tempLink);
                    window.URL.revokeObjectURL(blobURL);
                }
            }
        }
    };
</script>

